﻿using B.Z.BasicData.API.Read.Application.User;
using B.Z.BasicData.API.Read.DTO;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RootHub
{
    public class UserHub:Hub
    {

        private readonly IMediator _mediator;

        // 构造函数注入 IMediator
        public UserHub(IMediator mediator)
        {
            _mediator = mediator;
        }
        /// <summary>
        /// 当客户端连接到 Hub 时自动执行
        ///自动将新连接加入到 "LoginMessage" 组
        /// 确保所有连接都能接收登录通知
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, "LoginMessage");
            await base.OnConnectedAsync();
        }

        /// <summary>
        /// 登录后发送消息
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task SendLoginNotification(string username,string password)
        {
            var user = await _mediator.Send(new LoginQueryCommand(username,password));
            if (user != null)
            {   
                // 向所有连接的客户端发送登录通知
                await Clients.All.SendAsync("UserLoginNotification", user.Message);
                //向指定客户发送自己的Token
                await Clients.Caller.SendAsync("OnwerToken", user.Token);
            }
        }
        /// <summary>
        /// 当客户端断开连接时自动执行
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await base.OnDisconnectedAsync(exception);
        }
        /// <summary>
        /// 将当前连接的客户端加入到 "LoginMessage" 组
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task JoinGroup(string username)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, "LoginMessage");
        }

       
    }
}
